package ictbk.ttmk51.grapro.app;

import ictbk.ttmk51.grapro.app.common.MyActivity;
import ictbk.ttmk51.grapro.app.service.GetWebservice;
import ictbk.ttmk51.grapro.app.utils.EmailParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class LoginActivity extends MyActivity{
	
	private String USERNAME;
	private String PASSWORD;
	public static int USER_ID;
	
	Handler myHandler = new Handler();
	private SharedPreferences mShareRefs;
	
	private static final String	STRING_NAME_USERSETTING	= "USER REFERENCES";
	
	private Button btnExit;
	private Button btnLogin;
	
	public void setUsername(String USERNAME){
		this.USERNAME = USERNAME;
	}
	
	public void setPassword(String PASSWORD){
		this.PASSWORD = PASSWORD;
	}
	
	public String getUsername(){
		return USERNAME;
	}
	public String getPassword(){
		return PASSWORD;
	}
	
	public static int getUserID() {
		return USER_ID;
	}
	
	public void saveInfoLogin(String key, String value){
		mShareRefs = getSharedPreferences(STRING_NAME_USERSETTING, Activity.MODE_PRIVATE);
		Editor editor = mShareRefs.edit();
		if(value.trim().equals("")){
			editor.clear();
		}else{
			editor.putString(key, value);
		}
		
		editor.commit();
	}
	
	public String getSetting(String key){
		mShareRefs = getSharedPreferences(STRING_NAME_USERSETTING, Activity.MODE_PRIVATE);
		return mShareRefs.getString(key, "");
	}
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_LEFT_ICON);
        setContentView(R.layout.login_screen);
        setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.backup_data);
        
        btnLogin = (Button)findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new OnClickListener() {
        	
			@Override
			public void onClick(View v) {
				Login();
			}
		});
        
        btnExit = (Button)findViewById(R.id.btnExit);
        btnExit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				clickExit();
			}
		});
        
        //exit application from child activity
        if(getIntent().getBooleanExtra("EXIT", false)){
        	finish();
        }
        
        ((EditText)findViewById(R.id.edtUsername)).setText(getSetting("username"));
        ((EditText)findViewById(R.id.edtPassword)).setText(getSetting("password"));
    }
    
    //Click Login Button
    public void Login(){
//    	final ProgressDialog pd = showProgressDialog("Login", "Please wait...",R.drawable.lock, false);
//		final Thread threadLogin = new Thread(){
//			public void run(){
//				try{
//					final String Username = ((EditText)findViewById(R.id.edtUsername)).getText().toString();
//			        final String Password = ((EditText)findViewById(R.id.edtPassword)).getText().toString();
//			        if(Username.equals("")&&Password.equals("")){
//			        	myHandler.post(new Runnable() {
//							
//							@Override
//							public void run() {
//								// TODO Auto-generated method stub
//								pd.dismiss();
//								showToast("Please enter Username && Password");
//							}
//						});
//			        }else if(Username.equals("")){
//			        	myHandler.post(new Runnable() {
//							
//							@Override
//							public void run() {
//								// TODO Auto-generated method stub
//								pd.dismiss();
//								showToast("Please enter Username");
//							}
//						});
//			        }else if(Password.equals("")){
//			        	myHandler.post(new Runnable() {
//							
//							@Override
//							public void run() {
//								// TODO Auto-generated method stub
//								pd.dismiss();
//								showToast("Please enter Password");
//							}
//						});
//			        }else{
//			        	String str = GetWebservice.CheckLogin(Username, Password);
//			        	USER_ID = Integer.parseInt(str.trim());
//			        	if(USER_ID == -1){
//			        		myHandler.post(new Runnable() {
//								
//								@Override
//								public void run() {
//									// TODO Auto-generated method stub
//									pd.dismiss();
//									showToast("Wrong Username or Password");
//								}
//							});
//			        	}else{
//			        		Log.i("Checked Login", "Đăng nhập thành công");
//			        		USERNAME = Username;
//			        		PASSWORD = Password;
//			        		final boolean chk = ((CheckBox)LoginActivity.this.findViewById(R.id.CheckBox01)).isChecked();
//			        		myHandler.post(new Runnable() {
//								
//								@Override
//								public void run() {
//									// TODO Auto-generated method stub
//									if(chk){
//										LoginActivity.this.saveInfoLogin("username", Username);
//										LoginActivity.this.saveInfoLogin("password", Password);
//									}else{
//										LoginActivity.this.saveInfoLogin("username", "");
//										LoginActivity.this.saveInfoLogin("password", "");
//									}
//									
									Intent intent = new Intent(LoginActivity.this, MainActivity.class);
									startActivity(intent);
									
//									pd.dismiss();
//								}
//							});
//			        	}
//			        }
//				}catch(Exception e){
//					Log.i("Lỗi", "Lỗi Kết Nối");
//					myHandler.post(new Runnable() {
//						
//						@Override
//						public void run() {
//							// TODO Auto-generated method stub
//							showMessageDialog("Error Connect", R.drawable.error_icon, "\nPlease try again");
//							pd.dismiss();
//						}
//					});
//					
//				}
//			}
//		};
//		threadLogin.start();
    }
    
    //Create New Account
    public boolean checkAccountInfo(String username, String password, String confirmPassword, String email){
    	if(username.equals(null)||username.trim().equals("")){
    		showToast("Enter Username!");
    		return false;
    	}else if(password.equals(null)||password.trim().equals("")){
    		showToast("Enter Password");
    		return false;
    	}else if(confirmPassword.equals(null)||confirmPassword.trim().equals("")){
    		showToast("Enter Confirm Password");
    		return false;
    	}else if(email.equals(null)||email.trim().equals("")){
    		showToast("Enter Email");
    		return false;
    	}else if(!password.trim().equals(confirmPassword.trim())){
    		showToast("Password not match!");
    		return false;
    	}else if(!new EmailParser(email).isValid()){
    		showToast("Email inValid!");
    		return false;
    	}else{
    		return true;
    	}
    }
    public void createNewAccount(){
    	
    	LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	View view = vi.inflate(R.layout.signup, null);
    	
    	final EditText txtUsername = (EditText)view.findViewById(R.id.txtUsername);
    	final EditText txtPassword = (EditText)view.findViewById(R.id.txtPassword);
    	final EditText txtConfirmPassword = (EditText)view.findViewById(R.id.txtConfirmPassword);
    	final EditText txtEmail = (EditText)view.findViewById(R.id.txtEmail);
    	
    	AlertDialog.Builder signUpScreen = new AlertDialog.Builder(this);
    	signUpScreen.setTitle("Create New Account");
    	signUpScreen.setIcon(R.drawable.new_account);
    	signUpScreen.setView(view);
    	
    	signUpScreen.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				final String username = txtUsername.getText().toString();
				final String password = txtPassword.getText().toString();
				String confirmPassword = txtConfirmPassword.getText().toString();
				final String email = txtEmail.getText().toString();
				
				if(checkAccountInfo(username, password, confirmPassword, email)){
					final ProgressDialog pd = showProgressDialog("Sigup", "Please wait...", R.drawable.create_new_account, false);
					new Thread(){
						public void run(){
							try{
								final String msg = GetWebservice.CreateNewAccount(username, password, email);
								myHandler.post(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										pd.dismiss();
										showToast(msg);
									}
								});
							}catch(Exception e){
								Log.i("Lỗi", "Sao lại lỗi nhỉ???");
							}
						}
					}.start();
					
				}
			}
		});
    	
    	signUpScreen.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
    	
    	signUpScreen.create().show();
    }
    
    //Revert Password - forgot password
    public boolean checkEmailInfo(String email){
    	if(email.equals(null)||email.trim().equals("")){
    		showToast("Enter email to revert!");
    		return false;
    	}else if(!new EmailParser(email).isValid()){
    		showToast("Wrong Gmail to revert!");
    		return false;
    	}else{
    		return true;
    	}
    }
    private void RevertPassword(){
    	AlertDialog.Builder forgotPasswordAlertDialog = new AlertDialog.Builder(this);
    	forgotPasswordAlertDialog.setTitle("Revert Account");
    	forgotPasswordAlertDialog.setIcon(R.drawable.restore_account);
    	
    	LayoutInflater vi = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
    	View view = vi.inflate(R.layout.restore_account, null);
    	
    	final EditText inputEmail = (EditText)view.findViewById(R.id.txtEmail);
    	
    	forgotPasswordAlertDialog.setView(view);
    	forgotPasswordAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				final String email = inputEmail.getText().toString();
				if(checkEmailInfo(email)){
					final ProgressDialog pd = showProgressDialog("Rever Password", "Please wait...", R.drawable.restore_account, false);
					new Thread(){
						public void run(){
							myHandler.post(new Runnable() {
								
								@Override
								public void run() {
									// TODO Auto-generated method stub
									String msg = GetWebservice.RevertPassword(email);
									if(!msg.equals(null)){
										pd.dismiss();
										showToast("Your Account restored! \n Please Check Your Gmail \n Password:" + msg);
									}else{
										pd.dismiss();
										showToast("Your Email not exited!"); //sao lai sai doan nay -forceclose!!!
									}
								}
							});
						}
					}.start();
				}
			}
		});
    	
    	forgotPasswordAlertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
    	
    	forgotPasswordAlertDialog.create().show();
    }
    
  //Option Login Option Menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.login_menu, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case R.id.signup:
			createNewAccount();
			break;
		case R.id.forgotPassword:
			RevertPassword();
			break;
		}
		return true;
	}
    
    public void clickExit(){
    	try{
			saveInfoLogin("username", "");
			saveInfoLogin("password", "");
			finalize();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finish();
    }
    
}
